package com.nacos.consumer.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.itheima.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author 邓向军
 * @date2021/4/25 19:10
 */
@Service
public class OrderService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    public Goods findGoodsById(int id)
    {
        List<ServiceInstance> instances = discoveryClient.getInstances("nacos-provider");
        if(CollUtil.isEmpty(instances))
        {
            return null;
        }
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String scheme = serviceInstance.getScheme();
        String url="http://" + host + ":" + port+"/goods/findOne/"+id;
        System.out.println("scheme: "+scheme);
        System.out.println("port: "+port);
        System.out.println("host: "+host);
        System.out.println("url: "+url);
        Goods goods = restTemplate.getForObject(url, Goods.class);
        if(ObjectUtil.isNotEmpty(goods))
        {
            return goods;
        }
        return  null;
    }
}
